package presentation.util;

import javax.el.ELContext;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ValueChangeEvent;
import javax.faces.event.ValueChangeListener;

import persistence.LibraryLocation;
import persistence.Subscription;
import presentation.view_helpers.SubscriptionBean;

public class SubscriptionValueChangeListener implements ValueChangeListener{

	private static final String NEW_SUBSCRIPTION_PAGE = "/new-subscription.xhtml";
	private static final String SUBSCRIPTION_DETAILS_PAGE = "/subscription-details.xhtml";
	@Override
	public void processValueChange(ValueChangeEvent vce)
			throws AbortProcessingException {
		System.out.println("VALUE CHANGED");
		FacesContext fctx = FacesContext.getCurrentInstance();
		ELContext elctx = fctx.getELContext();
		SubscriptionBean subBean = (SubscriptionBean) elctx.getELResolver().getValue(elctx, null, "subscriptionBean");
		Subscription oldCurrentSubscription = subBean.getCurrentSubscription();
		oldCurrentSubscription.setLocation((LibraryLocation)vce.getNewValue());
		
		String currentView = fctx.getViewRoot().getViewId(); 
		if (currentView.equals("/new-subscription.xhtml")) {
			fctx.getApplication().getNavigationHandler().handleNavigation(fctx, null, NEW_SUBSCRIPTION_PAGE + "?revisit=true");
		}
		else if (currentView.equals("/subscription-details.xhtml")) {
			fctx.getApplication().getNavigationHandler().handleNavigation(fctx, null, SUBSCRIPTION_DETAILS_PAGE + "?subscription_id="+subBean.getCurrentSubscriptionID());
		}
	}

}